package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    MinioClient minioClient;

    @Autowired
    MinioProperties properties;

    @Override
    public String upload(MultipartFile file) {
        try {
            //检查是否创建了桶信息
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(properties.getBucketName()).build());
            if (!bucketExists) { //桶不存在
                //创建新的桶(文件夹)
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(properties.getBucketName()).build());
                //设置桶的访问权限
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(properties.getBucketName()).config(createBucketPolicyConfig(properties.getBucketName())).build());
            }

            //获取上传文件的原始名字 比如: 1.jpg
            String filename =file.getOriginalFilename() ;
            //重命名
            //1.截取文件的后缀名字
            String suffixName = filename.substring(filename.lastIndexOf("."));
            //2. 拼接新的文件名字
            String newFileName=  UUID.randomUUID().toString()+System.currentTimeMillis()+suffixName;

            System.out.println("文件的类型："+file.getContentType());

            //上传文件
            minioClient.putObject(PutObjectArgs.builder().
                    bucket(properties.getBucketName()).
                    object(newFileName).
                    stream(file.getInputStream(), file.getSize(), -1).
                    contentType(file.getContentType()).build());

            //minio的资源地址 http://xxxx:9001/test/1.jpg
            return String.join("/", properties.getEndpoint(), properties.getBucketName(), newFileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }

    private String createBucketPolicyConfig(String bucketName) {

        return """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """.formatted(bucketName);
    }
}


